package com.shell.customer.accreditation.rx;

import com.shell.bee.base.exception.UnCheckMsgException;
import com.shell.bee.esign.vo.EsignAuthResponse;
import com.shell.customer.accreditation.AccreditEvent;
import com.shell.customer.accreditation.vo.AccreditationVo;
import com.shell.customer.accreditation.vo.UserVo;
import com.shell.customer.esign.service.EsignAuthTxService;
import com.shell.customer.po.CusAcct;
import com.shell.customer.po.CusRec;
import com.shell.customer.util.CustomerUtil;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class EsignAuthSubscriber extends OnErrorNotImplementedSubscriber<AccreditEvent> {
	@Autowired
	private EsignAuthTxService esignAuthTxService;

	public void onApplicationEvent(AccreditEvent event) {
		if (CustomerUtil.onEsign()) {
			AccreditationVo accreditationVo = event.getAccreditationVo();
			UserVo admin = accreditationVo.getAdministrator();
			List<UserVo> operators = accreditationVo.getOperators();
			CusRec cus = accreditationVo.getCustomerC();
			try {
				if (!"PERSONAL".equals(cus.getCusType())) {
					EsignAuthResponse response = this.esignAuthTxService.personTelecomAuth(admin);
					if (response.getErrCode() != 0) {
						throw new UnCheckMsgException("��������������������e������" + response.getMsg());
					}
					for (UserVo operator : operators) {
						response = this.esignAuthTxService.personTelecomAuth(operator);
						if (response.getErrCode() != 0) {
							throw new UnCheckMsgException(
									"������[" + operator.getUserName() + "]��������������e������" + response.getMsg());
						}
					}
					response = this.esignAuthTxService.authBaseInfo(cus);
					if (response.getErrCode() != 0) {
						throw new UnCheckMsgException("������������������e������" + response.getMsg());
					}
					CusAcct cusAcct = accreditationVo.getCusAcct();
					cusAcct.setCusId(cus.getCusId());
					EsignAuthResponse payResponse = this.esignAuthTxService.toPay(cusAcct, response.getServiceId());
					if (payResponse.getErrCode() != 0) {
						throw new UnCheckMsgException("��������������e������" + payResponse.getMsg());
					}
				}
			} catch (Exception e) {
				throw new UnCheckMsgException(e.getMessage());
			}
		}
	}
}
